<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus"; // 导入 Element Plus 组件
import FavoritesSidebar from "../components/FavoritesSidebar.vue";
import FolderHeader from "../components/FolderHeader.vue";
import FavoriteVideoCard from "../components/FavoriteVideoCard.vue";
import EmptyContent from "../components/EmptyContent.vue";
import {
  getFavoritesListApi,
  getFavoriteVideosApi,
  createFavoriteApi,
  updateFavoriteApi,
  unfavoriteVideoApi,
  deleteFavoriteApi,
} from "@/api/favorites";
import { useVideoPlayerStore } from '@/store/modules/videoPlayer';

const videoPlayerStore = useVideoPlayerStore();

const handleVideoClick = (video) => {
  videoPlayerStore.openVideoModal(video.video_id, video);
};

// 模拟用户收藏夹数据
// 收藏夹状态
const userFavorites = ref([]);
const currentFolderId = ref(null);
const isLoading = ref(false);
const folderVideosLoading = ref(false);
// 添加分页相关状态
const pageSize = ref(10); // 每页显示的视频数量
const currentPage = ref(1); // 当前页码
const hasMoreVideos = ref(true); // 是否还有更多视频
const isLoadingMore = ref(false); // 是否正在加载更多

// 当前选中的收藏夹
const currentFolder = computed(() => {
  return (
    userFavorites.value.find((folder) => folder.id === currentFolderId.value) ||
    null
  );
});

// 加载收藏夹列表
const loadFavorites = async () => {
  isLoading.value = true;
  try {
    const response = await getFavoritesListApi();
    // 循环向收藏夹列表中添加videos属性
    response.forEach((folder) => {
      folder.videos = [];
    });
    userFavorites.value = response || [];

    // 如果有收藏夹，默认选中第一个
    if (userFavorites.value.length > 0) {
      currentFolderId.value = userFavorites.value[0].id;
      // 加载第一个收藏夹的视频
      await loadFolderVideos(currentFolderId.value);
    }
  } catch (error) {
    console.error("获取收藏夹列表失败:", error);
    ElMessage.error("获取收藏夹列表失败");
  } finally {
    isLoading.value = false;
  }
};

// 选择收藏夹
async function selectFolder(folderId) {
  if (currentFolderId.value === folderId) return;

  currentFolderId.value = folderId;
  // 重置分页状态
  currentPage.value = 1;
  hasMoreVideos.value = true;

  // 获取选中收藏夹的视频
  const folder = userFavorites.value.find((f) => f.id === folderId);

  // 如果该收藏夹尚未加载视频或视频为空，则加载视频
  if (folder) {
    // 清空之前的视频
    folder.videos = [];
    await loadFolderVideos(folderId);
  }
}

// 加载指定收藏夹的视频
const loadFolderVideos = async (folderId) => {
  if (!folderId) return;

  if (currentPage.value === 1) {
    folderVideosLoading.value = true;
  } else {
    isLoadingMore.value = true;
  }

  try {
    // 修改API调用，传入分页参数
    const response = await getFavoriteVideosApi(folderId, {
      page: currentPage.value,
      limit: pageSize.value,
    });

    // 判断是否还有更多视频
    hasMoreVideos.value = response && response.length === pageSize.value;

    // 找到当前收藏夹并更新其视频列表
    const folderIndex = userFavorites.value.findIndex((f) => f.id === folderId);
    if (folderIndex !== -1) {
      const folder = userFavorites.value[folderIndex];

      if (currentPage.value === 1) {
        // 第一页时替换视频列表
        userFavorites.value[folderIndex] = {
          ...folder,
          videos: response || [],
        };
      } else {
        // 后续页面追加视频
        userFavorites.value[folderIndex] = {
          ...folder,
          videos: [...folder.videos, ...(response || [])],
        };
      }
    }
  } catch (error) {
    console.error("获取收藏夹视频失败:", error);
    ElMessage.error("获取收藏夹内容失败");
  } finally {
    folderVideosLoading.value = false;
    isLoadingMore.value = false;
  }
};

// 加载更多视频
const loadMoreVideos = async () => {
  if (!currentFolderId.value || !hasMoreVideos.value || isLoadingMore.value)
    return;

  currentPage.value += 1;
  await loadFolderVideos(currentFolderId.value);
};

// 监听滚动事件，实现滚动加载
const handleScroll = (event) => {
  const element = event.target;
  // 当滚动到底部时加载更多
  if (element.scrollHeight - element.scrollTop - element.clientHeight < 100) {
    loadMoreVideos();
  }
};

// 创建新收藏夹
async function createNewFolder(data) {
  console.log("创建新收藏夹:", data);
  const { name, description = "" } = data;
  if (!name || name.trim() === "") {
    ElMessage.warning("收藏夹名称不能为空");
    return;
  }

  try {
    const response = await createFavoriteApi({
      name: name.trim(),
      description: description.trim() || "",
    });

    console.log("新收藏夹创建成功:", response);

    response.videos = [];

    userFavorites.value.push(response);

    ElMessage.success("收藏夹创建成功");
  } catch (error) {
    console.error("创建收藏夹失败:", error);
    ElMessage.error("创建收藏夹失败");
  }
}

// 重命名收藏夹
async function renameFolder(folderId) {
  const folder = userFavorites.value.find((f) => f.id === folderId);
  if (!folder) return;

  ElMessageBox.prompt("请输入新的收藏夹名称", "重命名收藏夹", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: folder.name,
    inputPattern: /\S+/, // 至少有一个非空白字符
    inputErrorMessage: "收藏夹名称不能为空",
    inputPlaceholder: "请输入收藏夹名称",
    customClass: "rename-folder-dialog",
    roundButton: true,
  })
    .then(async ({ value }) => {
      if (value && value.trim() !== "" && value.trim() !== folder.name) {
        try {
          await updateFavoriteApi(folderId, { name: value.trim() });

          // 更新本地数据
          folder.name = value.trim();

          ElMessage.success("收藏夹重命名成功");
        } catch (error) {
          console.error("重命名收藏夹失败:", error);
          ElMessage.error("重命名收藏夹失败");
        }
      }
    })
    .catch(() => {
      // 用户取消，不做任何操作
    });
}

// 删除收藏夹
async function deleteFolder(folderId) {
  console.log("删除收藏夹:", folderId);
  const folder = userFavorites.value.find((f) => f.id === folderId);
  if (!folder) return;

  ElMessageBox.confirm(
    `确定要删除收藏夹 "${folder.name}" 吗？此操作不可恢复。`,
    "删除收藏夹",
    {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
      customClass: "delete-folder-dialog",
      confirmButtonClass: "confirm-delete-btn",
      cancelButtonClass: "cancel-delete-btn",
      draggable: true,
      closeOnClickModal: false,
    }
  )
    .then(async () => {
      try {
        await deleteFavoriteApi(folderId);

        // 从本地列表中移除
        const folderIndex = userFavorites.value.findIndex(
          (f) => f.id === folderId
        );
        if (folderIndex !== -1) {
          userFavorites.value.splice(folderIndex, 1);

          // 重新加载收藏夹列表，确保界面与服务器状态一致
          await loadFavorites();

          ElMessage.success("收藏夹已删除");
        }
      } catch (error) {
        console.error("删除收藏夹失败:", error);
        ElMessage.error("删除收藏夹失败");
      }
    })
    .catch(() => {
      // 用户取消，不做任何操作
    });
}

// 查看视频详情
function viewVideoDetail(videoId) {
  console.log("查看视频详情", videoId);
}

// 从收藏夹中移除视频
async function removeFromFavorites(videoId) {
  if (!currentFolderId.value) return;

  try {
    await unfavoriteVideoApi(currentFolderId.value, videoId);

    // 本地更新，找到当前收藏夹
    const folder = userFavorites.value.find(
      (f) => f.id === currentFolderId.value
    );

    if (folder) {
      // 从视频列表中移除
      const videoIndex = folder.videos.findIndex((v) => v.video_id === videoId);
      if (videoIndex !== -1) {
        folder.videos.splice(videoIndex, 1);
        // 更新视频计数
        folder.video_count = (folder.video_count || 0) - 1;
      }
    }

    ElMessage.success("已从收藏夹移除");
  } catch (error) {
    console.error("从收藏夹移除视频失败:", error);
    ElMessage.error("移除失败，请重试");
  }
}

// 组件挂载时加载收藏夹列表
onMounted(() => {
  loadFavorites();
});
</script>

<template>
  <div class="content-panel">
    <h3>我的收藏</h3>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-state">
      <el-skeleton :rows="3" animated style="width: 100%" />
    </div>

    <div v-else-if="userFavorites.length > 0" class="favorites-container">
      <!-- 收藏夹列表 -->
      <FavoritesSidebar
        :folders="userFavorites"
        :currentFolderId="currentFolderId"
        @select-folder="selectFolder"
        @create-folder="createNewFolder"
      />

      <!-- 收藏夹内容展示 -->
      <div class="favorites-content">
        <FolderHeader
          v-if="currentFolder"
          :folder="currentFolder"
          @rename="renameFolder"
          @delete="deleteFolder"
        />

        <!-- 收藏夹视频加载中 -->
        <div v-if="folderVideosLoading" class="folder-loading">
          <el-skeleton :rows="2" animated>
            <template #template>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  flex-wrap: wrap;
                  width: 100%;
                "
              >
                <el-skeleton-item
                  variant="image"
                  style="width: 180px; height: 260px; margin: 10px"
                />
                <el-skeleton-item
                  variant="image"
                  style="width: 180px; height: 260px; margin: 10px"
                />
                <el-skeleton-item
                  variant="image"
                  style="width: 180px; height: 260px; margin: 10px"
                />
                <el-skeleton-item
                  variant="image"
                  style="width: 180px; height: 260px; margin: 10px"
                />
              </div>
            </template>
          </el-skeleton>
        </div>

        <!-- 收藏夹有视频内容 -->
        <div
          v-else-if="
            currentFolder &&
            currentFolder.videos &&
            currentFolder.videos.length > 0
          "
          class="favorites-video-list"
          @scroll="handleScroll"
        >
          <FavoriteVideoCard
            v-for="video in currentFolder.videos"
            :key="video.id"
            :video="video"
            @view-detail="handleVideoClick(video)"
            @remove="removeFromFavorites"
          />

          <!-- 加载更多提示 -->
          <div v-if="isLoadingMore" class="loading-more">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>加载更多...</span>
          </div>

          <!-- 没有更多内容提示 -->
          <div
            v-if="!hasMoreVideos && currentFolder.videos.length > 0"
            class="no-more"
          >
            已加载全部内容
          </div>
        </div>

        <!-- 收藏夹为空 -->
        <EmptyContent
          v-else-if="currentFolder"
          icon="📂"
          text="此收藏夹暂无视频"
          :showButton="false"
        />
      </div>
    </div>

    <!-- 没有收藏夹 -->
    <EmptyContent
      v-else
      icon="📚"
      text="暂无收藏夹"
      buttonText="创建收藏夹"
      @action="() => createNewFolder({ name: '我的收藏' })"
    />
  </div>
</template>

<style scoped lang="scss">
.content-panel {
  display: flex;
  flex-direction: column;
  height: 100%;

  h3 {
    margin-top: 8px;
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 1.4rem;
    color: #ffffff;
    border-left: 4px solid #0096ff;
    padding-left: 12px;
  }
}

.loading-state {
  padding: 20px;
  background-color: #1f2129;
  border-radius: 12px;
}

.favorites-container {
  display: flex;
  gap: 24px;
  flex: 1;
  overflow: hidden;
}

.favorites-content {
  flex: 1;
  background-color: #1f2129;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.favorites-video-list {
  padding: 16px;
  overflow-y: auto;
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  grid-auto-rows: 320px;
  gap: 20px;
  align-content: start;
  height: 100%;
  min-height: 0;

  /* 自定义滚动条 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.15);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.25);
  }
}

.loading-more, .no-more {
  grid-column: 1 / -1; /* 占据所有列，保证单独一行显示 */
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
  color: #909399;
  font-size: 14px;
  height: 40px;
  margin-top: 10px;
}

.loading-more {
  .loading-icon {
    animation: rotating 2s linear infinite;
    margin-right: 8px;
  }
}

.no-more {
  color: #606266;
  padding: 12px;
  border-top: 1px solid rgba(255, 255, 255, 0.05);
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.folder-loading {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 自定义对话框样式 */
:global(.delete-folder-dialog),
:global(.rename-folder-dialog) {
  border-radius: 12px;
  background-color: #2a2c36;
}

:global(.delete-folder-dialog .el-message-box__header),
:global(.rename-folder-dialog .el-message-box__header) {
  background-color: #2a2c36;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:global(.delete-folder-dialog .el-message-box__title),
:global(.rename-folder-dialog .el-message-box__title) {
  color: #ffffff;
}

:global(.delete-folder-dialog .el-message-box__content),
:global(.rename-folder-dialog .el-message-box__content) {
  color: #e0e0e0;
  padding-top: 20px;
}

:global(.delete-folder-dialog .el-message-box__message),
:global(.rename-folder-dialog .el-message-box__message) {
  color: #e0e0e0;
}

:global(.rename-folder-dialog .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.08);
  box-shadow: none;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

:global(.rename-folder-dialog .el-input__inner) {
  color: #ffffff;
}

:global(.confirm-delete-btn) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:global(.confirm-delete-btn:hover) {
  background-color: #e04747;
  border-color: #e04747;
}

:global(.cancel-delete-btn) {
  border-color: #909399;
  color: #909399;
}
</style>
